# 参考：https://www.cnblogs.com/small-bud/p/9064674.html
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time
import json
import requests
from requests.cookies import RequestsCookieJar
import os
from lxml import etree

host_url = 'http://222.205.160.107/jwglxt/xtgl/login_slogin.html?language=zh_CN&_t=1578291435586'
second_url = 'http://222.205.160.107/jwglxt/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default&su=1708170228'
user_informations_url = 'http://222.205.160.107/jwglxt/xsxxxggl/xsgrxxwh_cxXsgrxx.html?gnmkdm=N100801&layout=default&su=1708170228'
user_grade_url = 'http://222.205.160.107/jwglxt/cjcx/cjcx_cxDgXscj.html?gnmkdm=N305005&layout=default&su=1708170228'
user_class_url = ''


def save_cookies(_account, _password):
    # chrome_options = Options()
    # 无头
    # chrome_options.add_argument('--headless')
    # chrome_options.add_argument('--disable-gpu')

    # chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])

    driver = webdriver.PhantomJS(executable_path='D:\云服务器用\线宽计算器\spider\phantomjs-2.1.1-windows\bin\phantomjs.exe')
    # driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',
    #                           options=chrome_options)
    time.sleep(1)
    driver.get(host_url)
    time.sleep(2)
    lt = time.time()
    # driver.switch_to.frame()
    # driver.find_element_by_xpath('//*[@id="ampNoLoginTool"]').click()
    driver.find_element_by_id('yhm').send_keys(_account)
    driver.find_element_by_id('mm').send_keys(_password)
    driver.find_element_by_id('dl').click()
    print('登录完成')
    driver.get(second_url)
    # driver.g
    cookies = driver.get_cookies()
    with open(account + '_cookies.txt', "w") as fp:
        json.dump(cookies, fp)
    print('cookies update complete')
    # print(driver.page_source)
    print(time.time() - lt)
    xml = etree.HTML(driver.page_source)

    name = xml.xpath('//*[@id="col_xm"]/p/text()')

    xuehao = xml.xpath('//*[@id="col_xh"]/p/text()')
    xingbie = xml.xpath('//*[@id="col_xbm"]/p/text()')
    # photo = xml.xpath('//*[@id="xsrxhZp"]/@src')
    # photo_url = ''
    print(xuehao)
    print(name)
    print(xingbie)
    # print(type(ids))
    driver.quit()


def read_cookies():
    ls = time.time()
    # chrome_options = Options()
    # # 无头
    # chrome_options.add_argument('--headless')
    # chrome_options.add_argument('--disable-gpu')

    # chrome_options.add_experimental_option('excludeSwitches', ['enable-automation'])
    driver = webdriver.PhantomJS(executable_path='D:\云服务器用\线宽计算器\spider\phantomjs-2.1.1-windows\bin\phantomjs.exe')
    # driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',
    #                           options=chrome_options)

    # 设置cookies前必须访问一次页面
    # driver.get(host_url)
    with open("cookies1.txt", "r") as fp:
        cookies = json.load(fp)
        # for cookie in cookies:
        # # 由于selenium的cookies不支持expiry，所以需要去掉
        # if "expiry" in cookie.keys():
        #     # dict支持pop的删除函数
        #     cookie.pop("expiry")
        for cookie in cookies:
            # cookie.pop('domain')  # 如果报domain无效的错误
            driver.add_cookie(cookie)

    # driver.get(host_url)
    # time.sleep(5)
    page = driver.get(second_url)
    print(page)
    print(time.time() - ls)
    time.sleep(30)


def use_request(_account):
    s = requests.session()
    s.verify = False
    s.headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.8',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.104 Safari/537.36"
    }
    # s.get(host_url)
    # 这里我们使用cookie对象进行处理
    jar = RequestsCookieJar()
    cookiename = _account + '_cookies.txt'
    print(cookiename)
    with open(cookiename, "r") as fp:
        cookies = json.load(fp)
        for cookie in cookies:
            jar.set(cookie['name'], cookie['value'])
    # time.sleep(6)
    # s.get(host_url)
    # 教务处
    # xnm 学年码 xqm 学期码 一学期 ：3 二学期：12 三学期 16 全部：空
    xqm = ['', '3', '12', '16']
    for year in range(2017, 2021):
        print(str(year) + '年---' + str(year + 1) + '年')
        post_data = {
            'xnm': str(year),
            'xqm': xqm[1],
            '_search': 'false',
            'queryModel.showCount': '15',
            'queryModel.currentPage': '1',
            'queryModel.sortName': '',
            'queryModel.sortOrder': 'asc',
            'time': '0',
        }
        # 不重要 拿掉了'nd': '1611836480726',

        r = s.post(
            'http://222.205.160.107/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=%s' % _account,
            data=post_data,
            cookies=jar)
        # print(r.status_code)
        grade_data = r.json()
        for k in range(1, 3 + 1):  # 学期
            if k is not 1:
                post_data['xqm'] = xqm[k]
                post_data['queryModel.currentPage'] = '1'
                r = s.post(
                    'http://222.205.160.107/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=%s' % _account,
                    data=post_data,
                    cookies=jar)
                grade_data = r.json()
            print('第%d学期' % k + '  共%s页' % grade_data['totalPage'])
            for j in range(0, int(grade_data['totalPage'])):  # 页数
                if j is not 0:
                    post_data['queryModel.currentPage'] = str(j + 1)
                    r = s.post(
                        'http://222.205.160.107/jwglxt/cjcx/cjcx_cxDgXscj.html?doType=query&gnmkdm=N305005&su=%s' % _account,
                        data=post_data,
                        cookies=jar)
                    grade_data = r.json()
                print('第%d页' % (j + 1) + '  共%s页' % grade_data['totalPage'])
                for i in grade_data['items']:
                    # print(i)
                    print('课程:' + i['kcmc'] + '  ' + '成绩:' + i['cj'] + '  ' + '学分:' + i['xf'] + '  ' + '绩点:' + i['jd'])
                print('>>>>>')
            print("!!!!!!!!!")
        print("##################################")


def _get_account_password():
    _account = input('请输入账号：')
    _password = input('请输入密码:')
    with open('./ap.txt', 'w', encoding='utf-8') as fp:
        fp.writelines(_account + '\n')
        # fp.writelines(account)
        fp.writelines(_password)
        fp.close()
    return _account, _password


def get_account_password():
    if not os.path.exists('./ap.txt'):
        print('未找到登录文件，请手动输入')
        _account, _password = _get_account_password()
    else:
        with open('./ap.txt', 'r', encoding='utf-8') as fp:
            lines = fp.readlines()
            fp.close()
            try:
                # split use to delte \n
                _account = lines[0].split('\n')[0]
                _password = lines[1]
                print('发现之前的账户信息')
                print('账号:' + _account)
                print('密码:' + _password)
                # answer1 = input('是否直接登录（y/n）:')
                answer1 = 'y'
                if answer1 is 'y':
                    pass
                else:
                    _account, _password = _get_account_password()
            except:
                print('信息不完整，请重新输入')
                _account, _password = _get_account_password()
    return _account, _password


if __name__ == '__main__':
    account, password = get_account_password()

    if os.path.exists(account + '_cookies.txt'):
        #     # read_cookies(account)
        use_request(account)
    #     pass
    else:
        save_cookies(account, password)
        use_request(account)
    # get Data
